<!DOCTYPE html>
<%@page import="com.tdcy.sys.util.ParamUtils"%>
<%@page import="com.tdcy.sys.util.UserUtils"%>
<%@page import="com.tdcy.biz.utils.CommonUtils"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="biztag"%>
<%@page import="com.tdcy.framework.util.StringUtils"%>
<%@page import="com.tdcy.sys.util.CodeTableUtils"%>
<%@page import="com.tdcy.framework.util.RequestUtils"%>
<%@page import="com.tdcy.framework.util.SessionUtils"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>配置管理中心</title>

	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<jsp:include page="../../hcommon.jsp"></jsp:include>
	<script type="text/javascript" src="${jsPath }/jquery.md5.js"></script>
	<link rel="stylesheet" type="text/css" href="${path }/resource/js/ztree/css/ztree.css" />
	<link rel="stylesheet" type="text/css" href="${path }/resource/js/ztree/css/zTreeStyle.css" />
	<script src="${path }/resource/js/ztree/js/jquery.ztree.all-3.4.min.js" ></script>
	<script src="${path }/resource/js/ztree/js/jquery.ztree.exhide-3.4.min.js" ></script>
	<%
		String userkindjson = CodeTableUtils.getCodeBeanJson("user_kind");
		String stajson = CodeTableUtils.getCodeBeanJson("staff_sta");
		String deptjson = CommonUtils.getDeptsJson();
		Integer userKind  = UserUtils.USER_KIND_STAFF;
	%>
</head>

<body class="gray-bg skin-1">
	<div class="wrapper wrapper-content animated fadeInRight">
		<div class="row">
			<div class="col-sm-12">
				<div class="ibox float-e-margins">
					<div class="ibox-title">
						<h5>
						用户管理</h5>
					</div>
					<div class="ibox-content">
					    <div>
					    	<div class="row">
								<div class="col-sm-3 col-md-3" >
									<div class="jqGrid_wrapper uadmin-grid-margin" >
								        <table id="queryGrid">
								        </table>
								        <div id="pager_queryGrid"></div>
									</div>
								</div>
								<div class="col-sm-9 col-md-9" style="text-align: left;" >
									 <form  id="staffform"  class="form-horizontal" >  
								       <div class="form-group">   
								         <label class="col-sm-2 control-label">登录名：</label> 
								        <div class="col-sm-10">  
								            <input class="form-control" name="loginUser"  id="loginUser"  datatype="*" nullmsg="不能为空"/>
								             <div class="Validform_checktip"></div>
								           
								       </div>  
								       </div>   
								       <div class="form-group">   
								        <label for="lastname" class="col-sm-2 control-label">密码：</label>   
								        <div class="col-sm-10">  
								         <input class="form-control" name="password"  id="password" /> <span style="color: blue;">默认密码为(<%=ParamUtils.getParamValue("default_password") %>)</span>
								         </div>  
								       </div> 
								        <div class="form-group">   
								        <label for="lastname" class="col-sm-2 control-label">用户名称：</label>   
								        <div class="col-sm-10">  
								        <input class="form-control" name="staffName"  id="staffName"  datatype="*" nullmsg="不能为空"/> 
								         <div class="Validform_checktip"></div>
								         </div>  
								       </div> 
								       <div class="form-group">   
								        <label for="lastname" class="col-sm-2 control-label">用户状态：</label>   
								        <div class="col-sm-10">  
								      	  <biztag:Comp-CodeSelect defaultValue="1" name="staffSta" code="staff_sta"/>
								         </div>  
								       </div> 
								       <div class="form-group">   
								         <label for="roleDesc" class="col-sm-2 control-label">部门：</label>
								        <div class="col-sm-10" >
									         <div class="form-inline">
									            <input class="form-control" name="deptName"  id="deptName" readonly="true" style="width: 180px;height: 32px;"/>
												<input name="deptId" type="hidden" id="deptId" />
												<button class="btn btn-sm btn btn-sm btn-primary" id="btnUpOk" onclick="javascript:showDept();return false;" ><span>选择</span></button>
												<div id="divUpMenu" style="display:none; height: 450px; overflow:auto;" align="center">
													<div style="height: 390px; overflow:auto;border: #d6d6dd 1px solid;;">
														<ul id="tvUp" class="ztree"></ul>
													</div>
												</div>
											</div>
								         </div>  
								       </div> 
								        <div class="form-group">   
								         <label for="roleDesc" class="col-sm-2 control-label">角色：</label>
								        <div class="col-sm-10">  
								          <div class="jqGrid_wrapper uadmin-grid-margin" >
										        <table id="rolequeryGrid">
										        </table>
										        <div id="rolepager_queryGrid"></div>
											</div>
								         </div>  
								       </div> 
								     </form> 
									    <div style="text-align: center;margin-top: 2px;margin-bottom: 2px;">
											<button class="btn btn-sm btn btn-sm btn-primary" onclick="javascript:doAdd();" ><span>新增</span></button>
											<button class="btn btn-sm btn btn-sm btn-info"  onclick="javascript:doSave();" ><span>保存</span></button>
											<button class="btn btn-sm btn btn-sm btn-danger" onclick="javascript:doDel();" ><span>删除</span></button>
										</div>
									</div>
								</div>
								
							</div>
						</div>
					</div>	
				</div>
			</div>
		</div>
	</div>
</body>


<script type="text/javascript">
	var curUserId;
	var NEWID = "-100";
	var curUserId; //当前选择的部门id
	var userkindjson =  <%=userkindjson%>;
    var stajson = <%=stajson%>;
    var deptjson = <%=deptjson%>;
    var curUserInfo;
	
	var _deptTree;//当前部门树对象
	var staffdata; //所有的部门信息
	var reloadFlag = false;
	
	var userKind = "<%=userKind%>";
	
	var formValid = null;
	$(document).ready(function() {
		formValid = AppKit.formTipValidate("staffform");
		
		setEmptyInfo();
		curUserId = NEWID;
		
		initQueryGrid();
		initRoleQueryGrid();
		initUI();
	});
	
	function initUI(){
		var url ="${path}/sys/getallrole";
		AppKit.postJSON(url, null, function(json){
			if (!AppKit.checkJSONResult(json)) {
	            return;
	        }
			console.log(json.data);
			AppKit.renderRadios("rolediv", json.data, "roleId", "roleName", "roleId");
		});
	}
     
	function initQueryGrid() {
		var queryParams = {};
		var colModel=[];
	    var col2={label: '登录名', name: 'loginUser', align: 'center',width: 120,sortable:true,};
	    colModel.push(col2);
        var col2={label: '用户名称', name: 'staffName', align: 'center',width: 120,sortable:true,};
        colModel.push(col2);
	    var col1={label: '用户状态', name: 'staffSta', align: 'center',width: 120,sortable:true, formatter:staffStaFormatter};
	    colModel.push(col1);
        var col2={label: '部门', name: 'deptId', align: 'center',width: 120,sortable:true, formatter:deptFormatter};
        colModel.push(col2);
	    var col5={label: 'staffId', name: 'staffId', align: 'center',width: 200,sortable:true,hidden:true};
	    colModel.push(col5);
	        
		var settings={
	       postData: queryParams,
	       styleUI : 'Bootstrap',
		    mtype: "post",
		    url: "${path}/sys/querystaff",
		    prmNames:{//请求参数格式预处理
		          page:"page",
		          rows:"rows", 
		          sort:"sort",
		          order: "order"
		    },
	       datatype: "json",
	       colModel:colModel,
	       pageable: false,
		    page: 1,
	       rowNum: '-1',
	       multiSort: true,
		    sortable: true,
		    sortname: "id",
		    sortorder: "asc",
		    multiselect: false,
		    shrinkToFit: true,
		    height: 550,
		    shrinkToFit: true,
		   
		    jsonReader: {//返回参数格式处理
		        root: "data"
		    },
		    rownumbers: false,
		    multikey: "true",
		    autowidth: true,
		    onSelectRow:onUserClick
	      };
	      $("#queryGrid").jqGrid(settings);
	  };
	  
	  function initRoleQueryGrid() {
			var queryParams = {};
			var colModel=[];
		   var col1={label: '用户类型', name: '', align: 'center',width: 120,sortable:true, formatter:userKindFormatter};
		      colModel.push(col1);
		   var col2={label: '角色名称', name: 'roleName', align: 'center',width: 120,sortable:true,};
		      colModel.push(col2);
	      var col2={label: '角色代码', name: 'roleCode', align: 'center',width: 120,sortable:true,};
	      colModel.push(col2);
	      var col2={label: '描述', name: 'roleDesc', align: 'center',width: 120,sortable:true,};
	      colModel.push(col2);
		   var col5={label: 'roleId', name: 'roleId',  key: true, align: 'center',width: 200,sortable:true,hidden:true};
		      colModel.push(col5);
		      var col5={label: 'userKind', name: 'userKind', align: 'center',width: 200,sortable:true,hidden:true};
		      colModel.push(col5);
		        
			var settings={
		       postData: queryParams,
		       styleUI : 'Bootstrap',
			    mtype: "post",
			    url: "${path}/sys/getallrole",
			    prmNames:{//请求参数格式预处理
			          page:"page",
			          rows:"rows", 
			          sort:"sort",
			          order: "order"
			    },
		       datatype: "json",
		       colModel:colModel,
		       pageable: false,
			    page: 1,
		        rowNum: '-1',
		        multiSort: true,
			    sortable: true,
			    sortname: "id",
			    sortorder: "asc",
			    multiselect: true,
			    shrinkToFit: true,
			    height: 250,
			    shrinkToFit: true,
			   
			    jsonReader: {//返回参数格式处理
			        root: "data"
			    },
			    rownumbers: false,
			    multikey: "true",
			    autowidth: true,
		      };
		      $("#rolequeryGrid").jqGrid(settings);
		  };
	  
	  
	  function reloadTable(){
			$("#queryGrid").trigger("reloadGrid"); //重新载入    
		}

	function onUserClick() {
		setEmptyInfo();

		var id=$('#queryGrid').jqGrid('getGridParam','selrow');
		var rowData = $('#queryGrid').jqGrid('getRowData',id);
		if (rowData) {
			if(curUserId == rowData.staffId){
				return;
			}
			
			curUserId = rowData.staffId;
		    var url ="${path}/sys/getstaffinfo";
			AppKit.postJSON(url, {"staffId": curUserId }, showStaffInfo);
		}
	}

	function showStaffInfo(json){
		 if(!AppKit.checkJSONResult(json)){
	            return;
	      }
	      var data = json.data;
	      
	      if(data){
		      var staffinfo = data.staffEO;
		      if(staffinfo){
			      for(var i in staffinfo){
				      $("#staffform #"+i).val(staffinfo[i]);
				  }
			      
			      $("#staffform #"+i).val(staffinfo["staffSta"]);
			      
			      var userkind =staffinfo["userKind"];
			      if(userkind == "9"){
			    	    $("#ttinfo").html("内置用户不能更新、删除");
						$("#savebtn").hide();
						$("#delbtn").hide();
					}else{
						$("#ttinfo").html("");
						$("#savebtn").show();
						$("#delbtn").show();
					}
		      }
		      curUserId = staffinfo.staffId;
		      
	    	  var roleinfo = data.roleList;
	    	  
	    	  $("rolequeryGrid").trigger("reloadGrid");
	    	  
	    	  if(roleinfo){
    	     	 for(var i=0;i<roleinfo.length;i++){
                     var roleid = roleinfo[i].roleId;
                     $("#rolequeryGrid").jqGrid('setSelection',roleid);
             	 }
	    	 }
	    	  if(staffinfo["deptId"]){
	    		  showDeptName(staffinfo["deptId"]);
	    	  }
		  }
	      
	      $("#loginUser").attr("readonly","readonly");

	      curUserInfo =  $("#staffform").serializeObject();
	}
	
	 function showDeptName(deptId){
	    	var upDeptName = "";
	    	var upDeptId = "";
	    	var upDept = {};
	    	if(deptId=="0"){
	    		upDept["deptId"] = "0";
	    		upDept["deptUpId"] = "";
	    		upDept["deptName"] = jsName;
	    	}else{
	    		upDept = findDept(deptId);
	    	}
	    	
	        if(upDept){
	        	upDeptName = upDept.deptName;
	        	upDeptId = upDept.deptId;
	        }
	        $('#staffform #deptName').val(upDeptName);
	        $('#staffform #deptId').val(upDeptId);
	  }
	 
	 function findDept(deptId) {
     var dept = null;
     for (var i in deptjson) {
         if (deptjson[i].deptId == deptId) {
             dept = deptjson[i];
             break;
         }
     }

     return dept;
  }
	
	 function showDept() {
		 url = "${path}/views/jsp/system/getDept";
		 AppKit.openWindow(url,'选择部门',400,400,function(json){
			  $('#staffform #deptName').val(json["deptName"]);
		      $('#staffform #deptId').val(json["deptId"]);
		 });
	}
	
	function doSave(){
		var flag = formValid.check();
		if(!flag){
			return;
		}
		
		
	    if($("#staffNo").val()==''){
			AppKit.showTipMessage("请选择员工");
			return;
		}

		var refinfo =  $("#staffform").serializeObject();
		
		var ids=$('#rolequeryGrid').jqGrid('getGridParam','selarrrow');
		 var arras = new Array();
        for (var i = 0; i < ids.length; i++) {
       	   var rowData = $("#rolequeryGrid").jqGrid('getRowData',ids[i]);
       	 	arras.push(rowData.roleId);
        }
        
        refinfo["roleinfo"] = arras.join(",");
        
		if(refinfo["password"]){
			refinfo["password"] = $.md5(refinfo["password"]);
		}
	    if(curUserId == NEWID){
            url ="${path}/sys/addstaff";
        }else{
        	refinfo["staffId"] = curUserId;
        	refinfo["loginUser"] = $("#loginUser").val();
            url ="${path}/sys/updatestaff";
        }
	    
        AppKit.postJSON(url,refinfo, saveSuccess);
	}
	
	 function saveSuccess(json){
		 if(!AppKit.checkJSONResult(json)){
	            return;
	        }
	        if(json.data && json.data.staffId){
	        	curUserId = json.data.staffId;
	        }
	        
	        AppKit.showTipMessage(json.message);
	        curUserInfo =  $("#staffform").serializeObject();
	        
	        reloadTable();
	 }

	 function doAdd(){  
		 $("#loginUser").removeAttr("readonly");
		 setEmptyInfo();
		 curUserId = NEWID;
		 $("#addbtn").hide();
		 $("#savebtn").show();
			$("#delbtn").hide();
	 }

	  function setEmptyInfo(){
	        $("#staffform input").each(function(){
	            $(this).val("");
	        });
	        
	        $("#staffform select").each(function(){
	            $(this).val("");
	        });
	        
	        $("#staffform textarea").each(function(){
	            $(this).val("");
	        });
	        
            curUserInfo= "";
            
            $('#staffform #deptName').val('');
	        $('#staffform #deptId').val("");
	        $('#staffform #staffSta').val("1");
	        
	        $("#rolequeryGrid").trigger("reloadGrid");
	    }

	   function doDel() {
	        if(curUserId == NEWID ){
	            AppKit.showTipMessage("请选择要删除的记录");
	            return;
	        }
	        if(curUserId == 0 ){
	            AppKit.showTipMessage("admin用户不允许删除");
	            return;
	        }
	        //return;
	        AppKit.showConfirmMessage(function(){
			var url ="${path}/sys/delstaff";
	        AppKit.postJSON(url, {"staffId": curUserId }, delSuccess);},"确认删除吗？");
	    }
	    
	    function delSuccess(json){
	        if(!AppKit.checkJSONResult(json)){
	            return;
	        }
	        
	        AppKit.showTipMessage(json.message,"",function(){
	        	   curUserId = NEWID;
	        	   reloadTable();
	   	        	setEmptyInfo();
	        });
	    }

	    function staffStaFormatter(val,opt,rec){
		       return AppKit.getCodeFormatter(val, rec, stajson);
		  }
	    function deptFormatter(val,opt,rec){
	    	for(var i=0;i<deptjson.length;i++){
	    		var dept = deptjson[i];
	    		if(dept["deptId"] == val){
	    			return dept["deptName"];
	    		}
	    	}
			return "";
	    }
	    
	    function userKindFormatter(val, options, rec){
	        return AppKit.getCodeFormatter(rec.userKind, rec, userkindjson);
	   }
</script>
</html>